/*
 * This file is a part of the RMI Plugin for Eclipse tutorials.
 * Copyright (C) 2002-7 Genady Beryozkin
 * 
 * You are free to modify this file, as long as you leave
 * the following copyright:
 * 
 * This file is based on the Remote File System example of
 * the RMI Plug-in for Eclipse. The original code is 
 * Copyright (C) 2002-7 Genady Beryozkin
 */

package rmi.filesystem.server;

import java.io.File;
import java.io.FileNotFoundException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.InetAddress;
import java.net.UnknownHostException;
import java.rmi.RemoteException;
import java.rmi.registry.Registry;
import java.rmi.server.UnicastRemoteObject;

import rmi.filesystem.common.IRemoteFile;
import rmi.filesystem.common.IRemoteFileSystem;



/**
 * This class implements the remote file system interface.
 * 
 * @author Genady Beryozkin, rmi-info@genady.net
 */
public class RemoteFileSystemImpl extends UnicastRemoteObject implements
		IRemoteFileSystem 
{
	private static final long serialVersionUID = 6252905506329827787L;
	Registry rmiRegistry;
	/**
	 * Simple constructor that does nothing except exporting the object.
	 * @throws RemoteException
	 */
	protected RemoteFileSystemImpl() throws RemoteException {
		super();
	}

	/**
	 * Return the local hostname.
	 */
	public String getHost() throws RemoteException {
		try {
			return InetAddress.getLocalHost().getCanonicalHostName();
		} catch (UnknownHostException e) {
			throw new RemoteException("Could not retrieve the local host name", e);
		}
	}

	/**
	 * Return our local file system roots. On Windows return only the system
	 * drive. The method uses the {@link System#getenv()} method, which
	 * requires Java5.0, but it's ok, since the example requires Java5.0.
	 * 
	 * TODO: Retrieve only the real local roots and not any mapped drives.
	 */
	public IRemoteFile[] getRoots() throws RemoteException {
		IRemoteFile[] remoteRoots;
		String windrive = System.getenv("ARCHV");
		
		if (windrive != null) {
			remoteRoots = new IRemoteFile[1];
			remoteRoots[0] = new RemoteFileImpl(windrive);
		} else {
			File[] roots = File.listRoots();
			remoteRoots = new IRemoteFile[roots.length];
			for (int i = 0; i < roots.length; i++) {
				remoteRoots[i] = new RemoteFileImpl(roots[i].getPath());
			}			
		}
		return remoteRoots;
	}

	/* (non-Javadoc)
	 * @see demo.rmi.filesystem.common.IRemoteFileSystem#getRemoteFile(java.lang.String)
	 */
	public IRemoteFile getRemoteFile(String path) throws RemoteException {
				
		return new RemoteFileImpl(path);
		
	}

	
	
	
}
